package top.fengyulou.xiaofeng.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.fengyulou.xiaofeng.common.UuidUtil;
import top.fengyulou.xiaofeng.domain.*;
import top.fengyulou.xiaofeng.dto.*;
import top.fengyulou.xiaofeng.enums.ImageRelevanceTypeEnum;
import top.fengyulou.xiaofeng.enums.QuestionTypeEnum;
import top.fengyulou.xiaofeng.mapper.*;
import top.fengyulou.xiaofeng.mapper.my.MyExamMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName ExamService
 * @Description TODO
 * @Author qwer
 * @Date 2021/8/22 1:54
 * @Version 1.0
 */
@Service
public class ExamService {

    @Resource
    private ExamMapper examMapper;
    @Resource
    private ExamUserMapper examUserMapper;
    @Resource
    private MyExamMapper myExamMapper;
    @Resource
    private ExamPaperMapper examPaperMapper;
    @Resource
    private UserExamMapper userExamMapper;
    @Resource
    private UserExamQuestionMapper userExamQuestionMapper;
    @Resource
    private QuestionService questionService;
    @Resource
    private UserExamPaperMapper userExamPaperMapper;
    @Resource
    private ImageRelevanceMapper imageRelevanceMapper;
    @Resource
    private PaperQuestionService paperQuestionService;
    @Resource
    private PaperService paperService;
    @Resource
    private PaperQuestionRuleService paperQuestionRuleService;

    /**
     * 列表查询
     */
    public void list(ExamDto examDto) {
        //查询数据
        PageHelper.startPage(examDto.getPageNumber(), examDto.getPageSize());
        List<ExamDto> list = examMapper.list(examDto);
        PageInfo<ExamDto> pageInfo = new PageInfo<>(list);

        //返回结果
        examDto.setTotal(pageInfo.getTotal());
        examDto.setRows(list);
    }

    /**
     * 列表查询
     */
    public void getExamList(ExamDto examDto) {
        examDto.setPageSize(9);
        //查询数据
        PageHelper.startPage(examDto.getPageNumber(), examDto.getPageSize());
        List<ExamDto> list = examMapper.list(examDto);
        PageInfo<ExamDto> pageInfo = new PageInfo<>(list);

        //处理数据
        if (StringUtils.isNotBlank(examDto.getUserId())) {
            list.forEach(examDto1 -> {
                UserExamExample userExamExample = new UserExamExample();
                UserExamExample.Criteria criteria1 = userExamExample.createCriteria();
                criteria1.andUserIdEqualTo(examDto.getUserId());
                criteria1.andExamIdEqualTo(examDto1.getId());
                List<UserExam> userExams = userExamMapper.selectByExample(userExamExample);
                if (userExams.size() > 0) {
                    examDto1.setUserJoin(1);
                }
            });
        }

        //返回结果
        examDto.setTotal(pageInfo.getTotal());
        examDto.setRows(list);
        examDto.setPages(pageInfo.getPages());
    }

    /**
     * id查询
     */
    public ExamDto getById(String id) {
        return examMapper.getById(id);
    }

    /**
     * id查询
     */
    public ExamDto webGetById(ExamDto examDto) {
        return myExamMapper.webGetById(examDto);
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    @Transactional
    public void save(ExamDto examDto) {
        if (StringUtils.isNotBlank(examDto.getId())) {
            examDto.setUpdateTime(new Date());
            examDto.setLastUpdateUserId(examDto.getCurrentUserId());
            examMapper.update(examDto);
            //删除图片
            imageRelevanceMapper.deleteByRelevanceId(examDto.getId());
        } else {
            examDto.setId(UuidUtil.getShortUuid());
            examDto.setCreateTime(new Date());
            examDto.setCreateUserId(examDto.getCurrentUserId());
            examMapper.insert(examDto);
        }
        //添加图片
        ImageRelevanceDto imageRelevanceDto = new ImageRelevanceDto();
        imageRelevanceDto.setId(UuidUtil.getShortUuid());
        imageRelevanceDto.setImageId(examDto.getImageId());
        imageRelevanceDto.setRelevanceId(examDto.getId());
        imageRelevanceDto.setType(ImageRelevanceTypeEnum.EXAM.getCode());
        imageRelevanceDto.setCreateTime(new Date());
        imageRelevanceMapper.insert(imageRelevanceDto);
    }

    //删除
    @Transactional
    public void delete(String[] ids) {
        //删除考试
        examMapper.delete(ids);
        //删除试卷
        examPaperMapper.deleteByExamIds(ids);
        //删除用户
        examUserMapper.deleteByExamIds(ids);
    }

    /**
     * 保存用户
     *
     * @param examDto
     */
    @Transactional
    public void saveUser(ExamDto examDto) {
        List<ExamUser> list = new ArrayList<>();
        for (int i = 0; i < examDto.getUserIds().length; i++) {
            ExamUser examUser = new ExamUser();
            examUser.setId(UuidUtil.getShortUuid());
            examUser.setExamId(examDto.getId());
            examUser.setUserId(examDto.getUserIds()[i]);
            examUser.setCreateTime(examDto.getCreateTime());
            examUser.setCreateUserId(examDto.getCreateUserId());
            list.add(examUser);
        }
        examUserMapper.insertBatch(list);

        //修改用户数量
        ExamDto exam = new ExamDto();
        exam.setId(examDto.getId());
        exam.setUserNum(examUserMapper.countByExamId(examDto.getId()));
        exam.setUpdateTime(examDto.getCreateTime());
        examMapper.update(exam);
    }

    /**
     * 查询用户列表
     *
     * @param userDto
     */
    public List<UserDto> findUserList(UserDto userDto) {
        return myExamMapper.findUserListByExamId(userDto);
    }

    /**
     * 列表查询
     */
    public void userListPage(UserDto userDto) {
        //查询数据
        PageHelper.startPage(userDto.getPageNumber(), userDto.getPageSize());
        List<UserDto> list = examUserMapper.list(userDto);
        PageInfo<UserDto> pageInfo = new PageInfo<>(list);

        //返回结果
        userDto.setTotal(pageInfo.getTotal());
        userDto.setRows(list);
    }

    /**
     * 查询试卷列表
     *
     * @param paperDto
     * @return
     */
    public List<PaperDto> findPaperList(PaperDto paperDto) {
        return myExamMapper.findPaperListByExamId(paperDto);
    }

    /**
     * 保存试卷
     *
     * @param examDto
     */
    @Transactional
    public void savePaper(ExamDto examDto) {
        //添加试卷
        List<ExamPaper> list = new ArrayList<>();
        for (int i = 0; i < examDto.getPaperIds().length; i++) {
            ExamPaper examPaper = new ExamPaper();
            examPaper.setId(UuidUtil.getShortUuid());
            examPaper.setExamId(examDto.getId());
            examPaper.setPaperId(examDto.getPaperIds()[i]);
            examPaper.setCreateTime(new Date());
            examPaper.setCreateUserId(examDto.getCreateUserId());
            list.add(examPaper);
        }
        examPaperMapper.insertBatch(list);

        //修改试卷数量
        ExamDto exam = new ExamDto();
        exam.setId(examDto.getId());
        exam.setPaperNum(examPaperMapper.countByExamId(examDto.getId()));
        exam.setUpdateTime(new Date());
        examMapper.update(exam);
    }

    //用户加入考试
    public void userJoinExam(String userId, String examId) {
        UserExam userExam = new UserExam();
        userExam.setId(UuidUtil.getShortUuid());
        userExam.setUserId(userId);
        userExam.setExamId(examId);
        userExam.setCreateTime(new Date());
        userExamMapper.insert(userExam);
    }

    public List<PaperDto> getPaperListById(String examId, String userId) {
        PaperDto query = new PaperDto();
        query.setExamId(examId);
        query.setUserId(userId);
        List<PaperDto> webPaperListByExamId = myExamMapper.findWebPaperListByExamId(query);
        return webPaperListByExamId;
    }

    //提交试题
    public void addUserExamQuestion(UserExamQuestion userExamQuestion) {
        //试题
        QuestionDto byId = questionService.getById(userExamQuestion.getQuestionId());
        if (ObjectUtils.isEmpty(byId)) {
            return;
        }
        //试卷
        PaperDto paper = paperService.getById(userExamQuestion.getPaperId());
        if (ObjectUtils.isEmpty(paper)) {
            return;
        }
        //试题分数
        int score=0;
        if (paper.getType() == 1) {
            //固定试题分数
            PaperQuestionDto byPaperIdAndQstId = paperQuestionService.getByPaperIdAndQstId(userExamQuestion.getPaperId(), userExamQuestion.getQuestionId());
            if (ObjectUtils.isNotEmpty(byPaperIdAndQstId)) {
                score=byPaperIdAndQstId.getQstScore();
            }
        } else {
            //随机试题分数
            PaperQuestionRuleDto byPaperIdAndClassifyIdAndQstType = paperQuestionRuleService.getByPaperIdAndClassifyIdAndQstType(userExamQuestion.getPaperId(), byId.getClassifyId(), byId.getType());
            if (ObjectUtils.isNotEmpty(byPaperIdAndClassifyIdAndQstType)) {
                score=byPaperIdAndClassifyIdAndQstType.getQstScore();
            }
        }

        //提交试题
        if (!byId.getType().equals(QuestionTypeEnum.ZHUGUAN.getCode())) {
            //客观题
            if (byId.getAnswer().equals(userExamQuestion.getUserAnswer())) {
                //正确
                userExamQuestion.setStatus(1);
                userExamQuestion.setUserScore(score);
            } else {
                //错误
                userExamQuestion.setStatus(0);
                userExamQuestion.setUserScore(0);
            }
        } else {
            //主观题
            //待阅卷
            userExamQuestion.setStatus(2);
        }
        userExamQuestion.setUpdateTime(new Date());
        userExamQuestion.setLastUpdateUserId(userExamQuestion.getCurrentUserId());
        userExamQuestionMapper.update(userExamQuestion);
    }

    //添加用户试卷
    public UserExamPaper addUserExamPaper(UserExamPaper userExamPaper) {
        List<UserExamPaper> userExamPapers = userExamPaperMapper.list(userExamPaper);
        if (ObjectUtils.isEmpty(userExamPapers)) {
            userExamPaper.setId(UuidUtil.getShortUuid());
            userExamPaper.setCreateTime(new Date());
            userExamPaperMapper.insert(userExamPaper);
            return userExamPaper;
        } else {
            return userExamPapers.get(0);
        }
    }

    //修改试卷状态
    public void updateExamPaperStatus(UserExamPaper userExamPaper) {
        //修改试卷完成
        UserExamPaperDto userExamPaperDb = userExamPaperMapper.getById(userExamPaper.getId());
        if (ObjectUtils.isNotEmpty(userExamPaperDb) && userExamPaperDb.getStatus() == 0) {
            long useTime = new Date().getTime() - userExamPaperDb.getStartTime();
            if (useTime>userExamPaperDb.getTime()){
                useTime=userExamPaperDb.getTime();
            }
            userExamPaper.setUseTime(useTime);
            long countStatus2 = userExamQuestionMapper.countStatus2(userExamPaperDb.getId());
            if (countStatus2 > 0) {
                userExamPaper.setStatus(2);
            } else {
                userExamPaper.setStatus(1);
            }
            userExamPaper.setUpdateTime(new Date());
            userExamPaperMapper.updatePaperSubmit(userExamPaper);

            //修改用户完成状态
            //考试
            ExamDto exam = examMapper.getById(userExamPaperDb.getExamId());
            //完成数量
            long completeCount = userExamPaperMapper.getCountByUserExamId(userExamPaperDb.getUserExamId());
            if (exam.getPaperNum().longValue()==completeCount){
                examUserMapper.updateStatus(userExamPaperDb.getUserExamId());
            }
        }
    }

    //查询考试记录
    public List<QuestionDto> getQuestionRecord(ExamDto examDto) {
        return myExamMapper.getQuestionRecord(examDto);
    }

    public void getUserExamList(ExamDto examDto) {
        examDto.setPageSize(9);
        //查询数据
        PageHelper.startPage(examDto.getPageNumber(), examDto.getPageSize());
        List<ExamDto> list = examMapper.getUserExamList(examDto);
        PageInfo<ExamDto> pageInfo = new PageInfo<>(list);

        //返回结果
        examDto.setTotal(pageInfo.getTotal());
        examDto.setRows(list);
        examDto.setPages(pageInfo.getPages());
    }

    public void paperListPage(PaperDto paperDto) {
        //查询数据
        PageHelper.startPage(paperDto.getPageNumber(), paperDto.getPageSize());
        List<PaperDto> list = examPaperMapper.list(paperDto);
        if (ObjectUtils.isNotEmpty(list)) {
            for (PaperDto paper : list) {

            }
        }
        PageInfo<PaperDto> pageInfo = new PageInfo<>(list);

        //返回结果
        paperDto.setTotal(pageInfo.getTotal());
        paperDto.setRows(list);
    }

    public void paperMarkingListPage(PaperDto paperDto) {
        //查询数据
        PageHelper.startPage(paperDto.getPageNumber(), paperDto.getPageSize());
        List<PaperDto> list = userExamPaperMapper.markingList(paperDto);
        PageInfo<PaperDto> pageInfo = new PageInfo<>(list);

        //返回结果
        paperDto.setTotal(pageInfo.getTotal());
        paperDto.setRows(list);
    }
}
